<?php


namespace app\user\controller;


use think\Controller;
use think\Db;
use think\facade\Request;

/**
 * Class Department 部门与员工管理
 * @package app\user\controller
 */
class Department extends LoggingBase
{

    #region 员工列表
    public function StaffListing()
    {
        $UserID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;

        $CompanyData = Db::table('company')->field('UserID')->where("ID='$CompanyID'")->find();
        if($CompanyData['UserID'] == $UserID)$IsCompanyOwner = true;
        else $IsCompanyOwner = false;
        $this->assign('IsCompanyOwner',$IsCompanyOwner);

        $DepartmentData = Db::table('company_department')->field('ID, PID, Name, Describe')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='0'")->select();
        foreach ($DepartmentData as $Key => $Val) {
            $tID = $Val['ID'];
            $DepartmentData[$Key]['Lowers'] = $this->mb_LowerDepartments($tID, $CompanyID);
        }

        $Data = $this->mb_FormatDepartmentData($DepartmentData, 0);
        $this->assign('DepartmentData', $Data);

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('员工列表', 'StaffList', 'staff_list', $Css);
    }

    /**
     * 内部方法：获取下级部门
     * @param $PID
     * @param $CompanyID
     * @return array|\PDOStatement|string|\think\Collection
     */
    private function mb_LowerDepartments($PID, $CompanyID)
    {
        $DepartmentData = Db::table('company_department')->field('ID, PID, Name, Describe')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='$PID'")->select();
        foreach ($DepartmentData as $Key => $Val) {
            $tID = $Val['ID'];
            $DepartmentData[$Key]['Lowers'] = $this->mb_LowerDepartments($tID, $CompanyID);
        }
        return $DepartmentData;
    }

    /**
     * 内部方法：整合部门数据
     * @param $DepartmentData
     * @param $Count
     * @return array
     */
    private function mb_FormatDepartmentData($DepartmentData, $Count)
    {
        $Data = array();
        $Str = '';
        if ($Count > 0) {
            $Str .= '|';
            for ($i = 0; $i < $Count; $i++) {
                $Str .= '----';
            }
        }

        foreach ($DepartmentData as $Key => $Val) {
            array_push($Data, array('ID' => $Val['ID'], 'PID' => $Val['PID'], 'Name' => $Str . $Val['Name'], 'Describe' => $Val['Describe']));
            if (count($Val['Lowers']) > 0) {

                $LowersData = $this->mb_FormatDepartmentData($Val['Lowers'], $Count + 1);
                foreach ($LowersData as $tKey => $tVal) {
                    array_push($Data, $tVal);
                }
            }
        }
        return $Data;
    }

    /**
     * 接口：职位列表
     */
    public function mb_PostListing()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 9999999;

        $CompanyID = $this->m_User->CompanyID;
        $DepartmentID = Request::has('DepartmentID') ? Request::param('DepartmentID') : 0;  //0:当前企业下所有职位，Other：当前部门下的职位
        $Where = '';
        if($DepartmentID == 0){
            $Where .= " AND cd.CompanyID=$CompanyID ";
        } else {
            $Where .= " AND cdp.DepartmentID='$DepartmentID' ";
        }


//        if (!$DepartmentID) mb_OutMessage(ErrCode_Toast, '参数有误');
        $Count = Db::table('company_department_post')->alias('cdp')->leftJoin('company_department cd','cd.ID=cdp.DepartmentID')
            ->where("cdp.IsDeleted='0' $Where ")->count();

        $Data = Db::table('company_department_post')->alias('cdp')->field('cdp.ID,cdp.Name,cd.Name as DepartmentName,cdp.Describe')
            ->leftJoin('company_department cd','cd.ID=cdp.DepartmentID')
            ->where("cdp.IsDeleted='0' $Where ")
            ->page($Page)->limit($Limit)->order('cdp.DepartmentID', 'asc')->select();

        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 接口：直接上级列表
     */
    public function mb_SuperiorListing()
    {
        $CompanyID = $this->m_User->CompanyID;
        $DepartmentID = Request::has('DepartmentID') ? Request::param('DepartmentID') : 0;
        if (!$DepartmentID) mb_OutMessage(ErrCode_Toast, '参数有误');

        $DepartmentData = Db::table('company_department')->field('PID')->where("ID='$DepartmentID'")->find();
        if (!isset($DepartmentData)) mb_OutMessage(ErrCode_Toast, '该部门ID不存在');

        if ($DepartmentData['PID'] == 0) {
            //已经是最顶级部门
//            $Data = Db::table('user')->field('ID,Nick')->where("CompanyID='$CompanyID' AND DepartmentID='0' AND IsDeleted='0'")->select();
            $Data[] = array('ID' => 0, 'Nick' => '无');
        } else {
            //有上级部门
            $Data = Db::table('user')->field('ID,Nick')->where("CompanyID='$CompanyID' AND DepartmentID='" . $DepartmentData['PID'] . "' AND IsDeleted='0'")->select();
        }
        mb_OutMessage(ErrCode_Normal, '', $Data);
    }

    /**
     * 接口：新增或编辑员工
     */
    public function mb_SubmitStaff()
    {
        $ID = Request::has('ID') ? Request::param('ID') : 0;
        $Name = Request::has('Name') ? Request::param('Name') : '';
        $Nick = Request::has('Nick') ? Request::param('Nick') : '';
        $Sex = Request::has('Sex') ? Request::param('Sex') : 0;
        $Password = Request::has('Password') ? Request::param('Password') : '';
        $Phone = Request::has('Phone') ? Request::param('Phone') : '';
        $WeChat = Request::has('WeChat') ? Request::param('WeChat') : '';
        $QQ = Request::has('QQ') ? Request::param('QQ') : '';
        $Email = Request::has('Email') ? Request::param('Email') : '';
        $Remark = Request::has('Remark') ? Request::param('Remark') : '';
        $DepartmentID = Request::has('DepartmentID') ? Request::param('DepartmentID') : 0;
        $PostID = Request::has('PostID') ? Request::param('PostID') : 0;
        $SuperiorID = Request::has('SuperiorID') ? Request::param('SuperiorID') : 0;    //直接上级UserID

        if (!$Name) mb_OutMessage(ErrCode_Toast, '请输入账号');
        if (!$Nick) mb_OutMessage(ErrCode_Toast, '请输入姓名');
        if ($ID == 0 && !$Password) mb_OutMessage(ErrCode_Toast, '请输入密码');

        $CompanyID = $this->m_User->CompanyID;
        $Level = Level_CRMUser;

        Db::startTrans();
        try {
            $Data = array(
                'Name' => $Name,
                'Nick' => $Nick,
                'Sex' => $Sex,
                'EncPass' => md5($Password),
                'BasePass' => $Password,
                'Level' => Level_CRMUser,
                'Phone' => $Phone,
                'WeChat' => $WeChat,
                'QQ' => $QQ,
                'Email' => $Email,
                'Remark' => $Remark,
                'CompanyID' => $CompanyID,
                'DepartmentID' => $DepartmentID,
                'PostID' => $PostID,
                'SuperiorID' => $SuperiorID
            );
            if ($ID == 0) {
                //新增
                Db::table('user')->insert($Data);
            } else {
                //更新
                $Data['ID'] = $ID;
                Db::table('user')->update($Data);
            }
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 接口：员工列表
     */
    public function mb_StaffListing()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $CompanyID = $this->m_User->CompanyID;
        $DepartmentID = Request::has('DepartmentID') ? Request::param('DepartmentID') : 0;
        $Where = '';
        if ($DepartmentID) {
            $Where .= " AND u.DepartmentID='$DepartmentID' ";
        }

        $Count = Db::table('user')->alias('u')->where("u.IsDeleted='0' AND u.CompanyID='$CompanyID' $Where ")->count();
        $Data = Db::table('user')->alias('u')->field('u.ID, u.Name, u.Nick, u.Regist, u.Login, u.WeChat, u.QQ, u.Phone, u.Email, u.Sex, u.SuperiorID, u.DepartmentID, cd.Name AS DepartmentName, u.PostID, cdp.Name AS PostName, u1.Nick AS SuperiorName')
            ->leftJoin('company_department cd', 'cd.ID=u.DepartmentID')
            ->leftJoin('company_department_post cdp', 'cdp.ID=u.PostID')
            ->leftJoin('user u1', 'u1.ID=u.SuperiorID')
            ->where("u.IsDeleted=0 AND u.CompanyID=$CompanyID $Where ")->page($Page)->limit($Limit)->select();
        foreach ($Data as $Key => $Val){
            if($Val['Sex'] == 0){
                $Data[$Key]['SexStr'] = '';
            } else if($Val['Sex'] == 1){
                $Data[$Key]['SexStr'] = '男';
            } else if($Val['Sex'] == 2){
                $Data[$Key]['SexStr'] = '女';
            }
        }
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    #endregion

    #region 职位列表
    /**
     * 界面：职位列表
     */
    public function PostListing()
    {
        $CompanyID = $this->m_User->CompanyID;
        $this->assign('CompanyID',$CompanyID);
        //部门数据
        $DepartmentData = Db::table('company_department')->field('ID, PID, Name, Describe')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='0'")->select();
        foreach ($DepartmentData as $Key => $Val) {
            $tID = $Val['ID'];
            $DepartmentData[$Key]['Lowers'] = $this->mb_LowerDepartments($tID, $CompanyID);
        }

        $Data = $this->mb_FormatDepartmentData($DepartmentData, 0);
        $this->assign('DepartmentData', $Data);

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('职位列表', 'PostList', 'post_list', $Css);
    }

    #endregion

    #region 公司组织结构

    /**
     * 界面：新增部门
     */
    public function Listing()
    {
        $CompanyID = $this->m_User->CompanyID;
        $DepartmentData = Db::table('company_department')->field('ID, PID, Name, Describe')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='0'")->select();
        foreach ($DepartmentData as $Key => $Val) {
            $tID = $Val['ID'];
            $DepartmentData[$Key]['Lowers'] = $this->mb_LowerDepartments($tID, $CompanyID);
        }

        $this->assign('CompanyID', $CompanyID);
        $Data = $this->mb_FormatDepartmentData($DepartmentData, 0);
        $this->assign('DepartmentData', $Data);

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('公司组织结构', 'DepartmentList', 'department_list', $Css);
    }

    public function mb_ChangeStaff()
    {
        $StaffID = Request::has('StaffID') ? Request::param('StaffID') : 0;
        $DepartmentID = Request::has('DepartmentID') ? Request::param('DepartmentID') : 0;
        $PostID = Request::has('PostID') ? Request::param('PostID') : 0;
        if (!$StaffID || !$DepartmentID || !$PostID) mb_OutMessage(ErrCode_Toast, '参数有误！');
        Db::startTrans();
        try {
            Db::table('user')->update(array(
                'ID' => $StaffID,
                'DepartmentID' => $DepartmentID,
                'PostID' => $PostID
            ));
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '变更成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 接口：获取部门列表
     */
    public function mb_GetDepartmentList()
    {
        $Data = $this->mb_GetDepartments($this->m_User->CompanyID,0);
        mb_OutMessage(ErrCode_Normal,'',$Data);
    }

    private function mb_GetDepartments($CompanyID, $PID)
    {
        $Data = Db::table('company_department')->field('ID as id,PID,Name as title')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='$PID'")->select();
        if(count($Data) != 0) {
            foreach ($Data as $Key => $Val)
            {
                $Data[$Key]['children'] = $this->mb_GetDepartments($CompanyID, $Val['id'], $Data);
                $Data[$Key]['spread'] = true;
            }
        }
        return $Data;
    }
//    /**
//     * 接口：新增或编辑部门
//     */
//    public function mb_Submit()
//    {
//        $PID = Request::has('PID') ? Request::param('PID') : 0;
//        $Name = Request::has('Name') ? Request::param('Name') : '';
//        $Desc = Request::has('Desc') ? Request::param('Desc') : '';
//        if (!$PID || !$Name || !$Desc) {
//            mb_OutMessage(ErrCode_Toast, '参数有误！');
//        }
//        Db::startTrans();
//        try {
//            Db::table('company_department')->insert(array(
//                'CompanyID' => $this->m_User->CompanyID,
//                ''
//            ));
//            Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//        }
//
//    }

    /**
     * 接口：删除职位
     */
    public function mb_DeletePost()
    {
        $ID = Request::has('ID') ? Request::param('ID') : 0;    //职位ID
        $StaffCount = Db::table('user')->where("IsDeleted='0' AND PostID='$ID'")->count();
        if ($StaffCount > 0) mb_OutMessage(ErrCode_Toast, '该职位下仍有员工，无法删除');

        Db::startTrans();
        try {
            Db::table('user')->where("PostID='$ID' AND IsDeleted='0'")->update(['PostID' => 0]);
            Db::table('company_department_post')->where("ID='$ID'")->update(['IsDeleted' => 1]);
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 接口：删除部门
     */
    public function mb_DeleteDepartment()
    {
        $ID = Request::has('ID') ? Request::param('ID') : 0;    //部门ID
        //查找下级部门
        if ($this->mb_IsHaveStaffs($ID)) mb_OutMessage(ErrCode_Toast, '该部门及下级部门仍有员工，无法删除');
        Db::startTrans();
        try {
            Db::table('company_department')->where("ID='$ID'")->update(['IsDeleted' => 1]);
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }


    /**
     * 内部接口：该部门级下级是否还有员工
     * @param $ID
     * @return bool
     */
    private function mb_IsHaveStaffs($ID)
    {
        //检查自己部門有沒有成員
        $StaffCount = Db::table('user')->where("IsDeleted='0' AND DepartmentID='$ID'")->count();
        if ($StaffCount > 0) return true;

        //检查下级部门有没有员工
        $LowerDepartment = Db::table('company_department')->field('ID')->where("IsDeleted='0' AND PID='$ID'")->select();
        foreach ($LowerDepartment as $Key => $Val) {
            if ($this->mb_IsHaveStaffs($Val['ID'])) return true;
        }
    }
//    /**
//     * 接口：部门列表
//     */
//    public function mb_DepartmentListing()
//    {
//        $CompanyID = $this->m_User->CompanyID;
//        $DepartmentData = Db::table('company_department')->field('ID, Name')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND PID='0'")->select();
//        foreach ($DepartmentData as $Key => $Val) {
//            $tID = $Val['ID'];
//            $DepartmentData['Lowers'] = $this->mb_LowerDepartments($tID, $CompanyID);
//        }
//
////        print_r($DepartmentData);
////        exit();
//
//        $Data = array();
//        $Data = $this->mb_FormatDepartmentData($DepartmentData, $Data, 0);
//        mb_OutMessage(ErrCode_Normal, '', $Data);
//    }


    #endregion

    #region 编辑部门
    #endregion

    #region 部门列表
    #endregion

    #region 新增员工
    #endregion

    #region 编辑员工
    #endregion

    #region 员工列表
    #endregion
}